package kaindorfcompany.webshop.productmanagement.frontend.servlets;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kaindorfcompany.webshop.productmanagement.backend.access.DbAccess;
import kaindorfcompany.webshop.productmanagement.backend.data.Ingredient;
import kaindorfcompany.webshop.productmanagement.backend.data.Product;
import kaindorfcompany.webshop.productmanagement.backend.exceptions.DbAccessFailureException;
import kaindorfcompany.webshop.productmanagement.frontend.servlets.util.ServletUtil;

/**
 * @date 11.06.2014
 * @author Thomas Jahoda
 */
@WebServlet("/admin/products")
public class ProductOverviewServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public ProductOverviewServlet() {
    }

    /**
     * Show an overview for the ingredigents
     * @param request
     * @param response
     * @throws javax.servlet.ServletException
     * @throws java.io.IOException
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            List<Product> products = DbAccess.getInstance().getProducts();
            for (Product product : products) {
                LinkedList<Ingredient> ingredientsOfProduct = DbAccess.getInstance().getIngredientsOfProduct(product.getId());
                product.setIngredients(ingredientsOfProduct);
            }
            request.setAttribute("products", products);
            ServletUtil.forwardToView(request, response, "showProducts");
        } catch (DbAccessFailureException ex) {
            ServletUtil.showGeneralError(ex.getMessage(), request, response);
            log(null, ex);
            return;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}
